/**
 * 研发项目Store
 * 优化版 - 使用小驼峰命名和新数据结构
 */
const { observable, action, runInAction } = require('mobx-miniprogram');
const dayjs = require('../../../../config/libs_config').dayjs;
const cloudHelper = require('../../../../config/project_helpers_config').cloudHelper;
const pageHelper = require('../../../../config/project_helpers_config').pageHelper;
const ResearchProjectModel = require('../../../../config/models_config').ResearchProjectModel;

// 创建项目Store
const projectStore = observable({
  // 可观察状态
  currentProject: null,
  projectList: [],
  loading: false,
  total: 0,
  pageSize: 20,
  currentPage: 1,
  
  // 分页控制参数
  pagination: { 
    page: 1, 
    size: 20, 
    total: 0, 
    hasMore: true 
  },
  
  // 过滤条件
  filters: { 
    search: '', 
    projectType: '', 
    status: '' 
  },
  
  // 获取加载状态
  get isLoading() {
    return this.loading;
  },
  
  // 设置加载状态
  setLoading: action(function(loading) {
    this.loading = loading;
  }),
  
  // 设置当前项目
  setCurrentProject: action(function(project) {
    this.currentProject = project;
  }),
  
  // 设置项目列表
  setProjectList: action(function(list) {
    this.projectList = list;
  }),
  
  // 设置分页信息
  setPagination: action(function(total, pageSize, currentPage) {
    this.total = total;
    this.pageSize = pageSize;
    this.currentPage = currentPage;
    
    // 同步更新pagination对象
    this.pagination = {
      page: currentPage,
      size: pageSize,
      total: total,
      hasMore: this.projectList.length < total
    };
  }),
  
  // 设置过滤条件
  setFilters: action(function(filters) {
    this.filters = { ...this.filters, ...filters };
    // 重置分页
    this.pagination.page = 1;
    this.currentPage = 1;
  }),
  
  // 加载项目列表
  loadProjectList: action(async function(params = {}, reset = false) {
    runInAction(() => {
      this.loading = true;
    });
    
    try {
      // 重置分页
      if (reset) {
        runInAction(() => {
          this.pagination.page = 1;
          this.currentPage = 1;
          this.projectList = [];
        });
      }
      
      // 默认参数
      const defaultParams = {
        page: this.pagination.page,
        size: this.pagination.size,
        search: this.filters.search || '',
        sortType: 'recent',
        status: this.filters.status || 'all',
        projectType: this.filters.projectType || ''
      };
      
      // 合并参数
      const queryParams = {...defaultParams, ...params};
      
      // 调用云函数获取项目列表
      const result = await cloudHelper.callCloudData('plm_research/list', queryParams, {
        title: '加载中',
        loading: true
      });
      
      // 设置项目列表和分页信息
      if (result && result.list) {
        runInAction(() => {
          // 根据是否重置决定如何处理列表数据
          if (reset) {
            this.projectList = result.list;
          } else {
            // 合并列表，避免重复
            const existingIds = new Set(this.projectList.map(p => p._id || p.id));
            const newItems = result.list.filter(p => !existingIds.has(p._id || p.id));
            this.projectList = [...this.projectList, ...newItems];
          }
          
          // 更新分页信息
          this.total = result.total || 0;
          this.pageSize = queryParams.size;
          this.currentPage = queryParams.page;
          
          // 更新pagination对象
          this.pagination = {
            page: queryParams.page,
            size: queryParams.size,
            total: result.total || 0,
            hasMore: this.projectList.length < (result.total || 0)
          };
          
          // 页码自增，为下次加载做准备
          if (!reset) {
            this.currentPage++;
            this.pagination.page++;
          }
        });
      }
      
      return result;
    } catch (error) {
      console.error('[项目Store] 加载项目列表错误:', error);
      throw error;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 加载更多项目
  loadMoreProjects: action(async function() {
    // 如果正在加载或者没有更多数据，直接返回
    if (this.loading || !this.pagination.hasMore) {
      return null;
    }
    
    // 调用加载项目列表方法，不重置数据
    return await this.loadProjectList();
  }),
  
  // 清除所有缓存
  clearAllCache: action(function() {
    // 实现清除缓存的逻辑
    console.log('[项目Store] 清除缓存');
    
    // 重置Store状态
    this.projectList = [];
    this.currentProject = null;
    this.total = 0;
    this.currentPage = 1;
    this.pagination = { page: 1, size: 20, total: 0, hasMore: true };
  }),
  
  // 加载项目详情
  loadProjectDetail: action(async function(id, showLoading = true) {
    if (!id) return null;
    
    runInAction(() => {
      this.loading = true;
    });
    
    try {
      // 调用云函数获取项目详情
      const params = { id };
      const options = showLoading ? { title: '加载中', loading: true } : {};
      
      const result = await cloudHelper.callCloudData('plm_research/detail', params, options);
      
      // 标准化项目数据结构 - 在旧字段转换为新小驼峰字段
      const project = this.standardizeProjectData(result);
      
      // 设置当前项目
      runInAction(() => {
        this.currentProject = project;
      });
      
      return project;
    } catch (error) {
      console.error('[项目Store] 加载项目详情错误:', error);
      throw error;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 创建项目
  createProject: action(async function(projectData) {
    runInAction(() => {
      this.loading = true;
    });
    
    try {
      // 检查必要字段
      const requiredFields = ['name', 'customerName', 'projectType', 'startDate', 'deadline'];
      for (const field of requiredFields) {
        if (!projectData[field]) {
          throw new Error(`${field}不能为空`);
        }
      }
      
      // 标准化项目数据 - 确保符合新的数据结构
      const data = this.prepareProjectData(projectData);
      
      // 调用云函数创建项目
      const result = await cloudHelper.callCloudData('plm_research/create', data, {
        title: '创建中',
        loading: true
      });
      
      // 添加到项目列表
      if (result && result.id) {
        // 获取完整项目信息
        const newProject = await this.loadProjectDetail(result.id, false);
        
        // 更新列表
        if (newProject && this.projectList.length > 0) {
          runInAction(() => {
            this.projectList.unshift(newProject);
          });
        }
      }
      
      return result;
    } catch (error) {
      console.error('[项目Store] 创建项目错误:', error);
      pageHelper.showModal('创建失败', error.message || '请稍后重试');
      throw error;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 更新项目
  updateProject: action(async function(id, projectData) {
    if (!id) return null;
    
    runInAction(() => {
      this.loading = true;
    });
    
    try {
      // 标准化项目数据
      const data = this.prepareProjectData(projectData);
      data.id = id;
      
      // 调用云函数更新项目
      const result = await cloudHelper.callCloudData('plm_research/update', data, {
        title: '更新中',
        loading: true
      });
      
      // 更新当前项目和列表
      if (result && result.id) {
        // 获取更新后的项目
        const updatedProject = await this.loadProjectDetail(id, false);
        
        // 更新列表中的项目
        runInAction(() => {
          const index = this.projectList.findIndex(p => p.id === id);
          if (index >= 0 && updatedProject) {
            this.projectList[index] = updatedProject;
          }
        });
      }
      
      return result;
    } catch (error) {
      console.error('[项目Store] 更新项目错误:', error);
      throw error;
    } finally {
      runInAction(() => {
        this.loading = false;
      });
    }
  }),
  
  // 准备项目数据 - 处理字段转换和默认值
  prepareProjectData(formData) {
    const now = Math.floor(dayjs().valueOf() / 1000);
    const isNewProject = !formData.id;
    
    // 处理日期
    let startDate = formData.startDate;
    let deadline = formData.deadline;
    
    // 转换日期格式为时间戳
    if (typeof startDate === 'string' && startDate.includes('-')) {
      startDate = dayjs(startDate).unix();
    }
    
    if (typeof deadline === 'string' && deadline.includes('-')) {
      deadline = dayjs(deadline).unix();
    }
    
    // 构建标准化的项目数据
    const projectData = {
      // 基础标识信息
      model: formData.model || formData.name,
      projectType: formData.projectType || formData.name,
      name: formData.name,
      
      // 分类与描述信息 - 直接使用原始值，不做映射
      projectTypeName: formData.projectTypeName,
      category: formData.category || '研发',
      description: formData.description || '',
      
      // 客户信息
      customerName: formData.customerName,
      
      // 项目状态信息 - 新项目时设置初始状态
      ...(isNewProject ? {
        level1: 1, // 项目审核
        level2: 'director', // 董事长审核
        level3: '',
        level4: '',
        statusDesc: '项目审核 > 董事长'
      } : {}),
      
      // 管理信息
      priority: formData.priority || 'normal',
      
      // 时间信息
      ...(isNewProject ? {
        createTime: now,
        updateTime: now,
        stateTime: now
      } : {
        updateTime: now
      }),
      
      startDate: startDate,
      deadline: deadline,
      planStartDate: startDate,
      planEndDate: deadline,
      
      // 样机信息
      hasSample: formData.hasSample || '无',
      sampleCount: formData.sampleCount || '',
      sampleImages: formData.sampleImages || [],
      
      // 其他专用参数
      ...(this.getSpecificParams(formData))
    };
    
    return projectData;
  },
  
  // 获取特定参数 - 根据项目类型返回特定参数
  getSpecificParams(formData) {
    // 处理applicationType到projectType的映射
    let specificParams = {};
    
    // 应用类型到项目类型的映射（保持与服务端一致）
    const appTypeMapping = {
      '磁编': 1,     // 电机控制类
      '霍尔': 1,     // 电机控制类
      '风机': 1,     // 电机控制类
      '水泵': 1,     // 电机控制类
      '电源': 2,     // 电源类
      '传感器': 3,    // 传感器类
      '其他': 4      // 其他类型
    };
    
    // 项目类型名称映射
    const projectTypeNames = {
      1: '电机控制类',
      2: '电源类',
      3: '传感器类',
      4: '其他类型'
    };
    
    // 如果已有明确的projectType数值，优先使用
    if (typeof formData.projectType === 'number') {
      specificParams.projectType = formData.projectType;
      // 如果没有提供projectTypeName，根据projectType设置
      if (!formData.projectTypeName) {
        specificParams.projectTypeName = projectTypeNames[formData.projectType] || '未知类型';
      } else {
        specificParams.projectTypeName = formData.projectTypeName;
      }
    } 
    // 如果projectType是字符串，尝试转换为数字
    else if (typeof formData.projectType === 'string' && !isNaN(parseInt(formData.projectType))) {
      specificParams.projectType = parseInt(formData.projectType);
      specificParams.projectTypeName = projectTypeNames[specificParams.projectType] || '未知类型';
    }
    // 如果有applicationType，根据映射表转换为数值类型的projectType
    else if (formData.applicationType && appTypeMapping[formData.applicationType]) {
      specificParams.applicationType = formData.applicationType;
      specificParams.projectType = appTypeMapping[formData.applicationType];
      specificParams.projectTypeName = projectTypeNames[specificParams.projectType];
    }
    // 默认为"其他类型"
    else {
      specificParams.projectType = 4; // 其他类型
      specificParams.projectTypeName = '其他类型';
    }
    
    // 确保applicationType字段存在
    if (formData.applicationType && !specificParams.applicationType) {
      specificParams.applicationType = formData.applicationType;
    }
    
    // 如果是电机控制类项目，添加特有参数
    const isMotorControl = 
      specificParams.projectType === 1 || 
      ['磁编', '霍尔', '风机', '水泵'].includes(formData.applicationType);
    
    if (isMotorControl) {
      Object.assign(specificParams, {
        // 直接返回表单中的特定参数
        workTemp: formData.workTemp,
        certification: formData.certification,
        lowPower: formData.lowPower,
        startupTime: formData.startupTime,
        conformalCoating: formData.conformalCoating,
        
        // 电机参数
        ratedVoltage: formData.ratedVoltage,
        maxPower: formData.maxPower,
        maxSpeed: formData.maxSpeed,
        polePairs: formData.polePairs,
        hasHall: formData.hasHall,
        hasFG: formData.hasFG,
        hasBrake: formData.hasBrake,
        
        // 控制参数
        controlMode: formData.controlMode,
        controlAlgorithm: formData.controlAlgorithm,
        rotation: formData.rotation,
        
        // 保护参数
        stallProtection: formData.stallProtection,
        overvoltageProtection: formData.overvoltageProtection,
        undervoltageProtection: formData.undervoltageProtection,
        temperatureProtection: formData.temperatureProtection,
        overcurrentProtection: formData.overcurrentProtection,
        currentLimitProtection: formData.currentLimitProtection,
        blockageProtection: formData.blockageProtection,
        phaseProtection: formData.phaseProtection
      });
    }
    
    return specificParams;
  },
  
  // 标准化项目数据 - 将老格式转换为新格式
  standardizeProjectData(data) {
    if (!data) return null;
    
    // 创建新的项目对象，保留原始ID，不做字段映射转换
    const project = {
      id: data._id || data.id,
      
      // 直接使用数据库中的字段，不做映射转换
      model: data.model || data.projectCode,
      projectType: data.projectType,
      name: data.name,
      code: data.code,
      
      // 分类与描述信息
      projectTypeName: data.projectTypeName,
      category: data.category,
      description: data.description,
      
      // 人员信息
      customerName: data.customerName,
      customerId: data.customerId,
      
      // 申请人信息
      applicantId: data.applicantId,
      applicantName: data.applicantName,
      
      // 项目人员信息
      projectLeadId: data.projectLeadId,
      projectLead: data.projectLead,
      teamMembers: data.teamMembers,
      
      // 项目管理和状态信息
      level1: data.level1,
      level2: data.level2,
      level3: data.level3,
      level4: data.level4,
      fullStatusDesc: data.fullStatusDesc, // 使用fullStatusDesc替代statusDesc
      priority: data.priority,
      
      // 开发状态
      developmentStatus: data.developmentStatus,
      
      // 完成度
      completionPercentage: data.completionPercentage,
      
      // 分支信息
      branchId: data.branchId,
      branchName: data.branchName,
      
      // 时间信息
      createTime: data.createTime,
      updateTime: data.updateTime,
      
      // 项目时间点
      startDate: data.startDate,
      endDate: data.endDate,
      deadline: data.deadline,
      
      // 计划时间点
      planStartDate: data.planStartDate,
      planEndDate: data.planEndDate,
      
      // 状态时间点
      stateTime: data.stateTime,
      stateExpireTime: data.stateExpireTime,
      
      // 样机信息
      hasSample: data.hasSample,
      sampleCount: data.sampleCount,
      sampleImages: data.sampleImages,
    };
    
    // 处理状态描述和开发状态
    if (!project.fullStatusDesc || !project.developmentStatus) {
      try {
        const statusHelper = require('../../../helpers/status_helper');
        
        // 生成完整状态描述
        if (!project.fullStatusDesc) {
          project.fullStatusDesc = statusHelper.getFullStatusDesc(project);
        }
        
        // 生成开发状态
        if (!project.developmentStatus) {
          project.developmentStatus = statusHelper.getDevelopmentStatus(project);
        }
      } catch (error) {
        console.error('处理状态信息失败:', error);
      }
    }
    
    // 电机控制类项目特有字段处理
    // 判断是否是电机控制类项目：
    // 1. 如果projectType是字符串类型，检查是否在电机控制类应用列表中
    // 2. 如果projectType是数字类型，检查是否等于1
    // 3. 检查applicationType是否在电机控制类应用列表中
    const isMotorControl = 
      (typeof project.projectType === 'string' && ['磁编', '霍尔', '风机', '水泵'].includes(project.projectType)) ||
      (typeof project.projectType === 'number' && project.projectType === 1) ||
      (project.applicationType && ['磁编', '霍尔', '风机', '水泵'].includes(project.applicationType));
    
    if (isMotorControl) {
      // 直接使用数据库中的特定字段，不做映射转换
      project.workTemp = data.workTemp;
      project.certification = data.certification;
      project.lowPower = data.lowPower;
      project.startupTime = data.startupTime;
      project.conformalCoating = data.conformalCoating;
      
      // 电机基本参数
      project.ratedVoltage = data.ratedVoltage;
      project.maxPower = data.maxPower;
      project.maxSpeed = data.maxSpeed;
      project.polePairs = data.polePairs;
      project.hasHall = data.hasHall;
      project.hasFG = data.hasFG;
      project.hasBrake = data.hasBrake;
      
      // 控制参数
      project.controlMode = data.controlMode;
      project.controlAlgorithm = data.controlAlgorithm;
      project.rotation = data.rotation;
      project.controlInterface = data.controlInterface;
      
      // PWM控制参数
      project.pwmStartDuty = data.pwmStartDuty;
      project.pwmStopDuty = data.pwmStopDuty;
      project.pwmDutyRange = data.pwmDutyRange;
      project.pwmFreqRange = data.pwmFreqRange;
      
      // VSP控制参数
      project.vspStartVoltage = data.vspStartVoltage;
      project.vspStopVoltage = data.vspStopVoltage;
      project.vspVoltageRange = data.vspVoltageRange;
      
      // 保护参数
      project.stallProtection = data.stallProtection;
      project.stallHoldTime = data.stallHoldTime;
      project.stallRestartTime = data.stallRestartTime;
      project.stallRestartCount = data.stallRestartCount;
      
      project.overvoltageProtection = data.overvoltageProtection;
      project.overvoltageValue = data.overvoltageValue;
      project.overvoltageRecoveryValue = data.overvoltageRecoveryValue;
      
      project.undervoltageProtection = data.undervoltageProtection;
      project.undervoltageValue = data.undervoltageValue;
      project.undervoltageRecoveryValue = data.undervoltageRecoveryValue;
      
      project.temperatureProtection = data.temperatureProtection;
      project.protectionTemp = data.protectionTemp;
      project.recoveryTemp = data.recoveryTemp;
      
      project.overcurrentProtection = data.overcurrentProtection;
      project.overcurrentValue = data.overcurrentValue;
      
      project.currentLimitProtection = data.currentLimitProtection;
      project.currentLimitValue = data.currentLimitValue;
      
      project.blockageProtection = data.blockageProtection;
      project.blockageDiameter = data.blockageDiameter;
      project.blockageHoldTime = data.blockageHoldTime;
      
      project.phaseProtection = data.phaseProtection;
    }
    
    return project;
  },

  // 更新项目数据
  updateProjectFromServer: action(function(data) {
    this.projectDetail = {
      // ... existing code ...
      projectLeadId: data.projectLeadId,
      projectLead: data.projectLead,
      // ... existing code ...
    };
  })
}); 

// 导出模块
module.exports = projectStore; 